package com.example.demo.core;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 项目启动加载 通道信息
 */
public class MyLoader5 extends ClassLoader {
    private String path;

    public MyLoader5(){}
    public MyLoader5(String path) {
        super(null);
        this.path = path;
    }

    public MyLoader5(String path,ClassLoader parten) {
        super(getSystemClassLoader());
        this.path = path;
    }

    /**
     * 查找 class 并重新加载
     * @param name class name
     * @return Class
     * @throws ClassNotFoundException
     */

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] data = this.getClass(name);
        return this.defineClass(name, data, 0, data.length);
    }

    /**
     * 加载class
     * @param name class name
     * @param resolve resolve
     * @return Class
     * @throws ClassNotFoundException
     */
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        if(name.contains("com.example.demo.channel.service.Impl")){
            return getSystemClassLoader().loadClass(name);
            //return this.findClass(name);
        }
        return getSystemClassLoader().loadClass(name);
    }

    /**
     * 获取class字节数组
     * @param name class name
     * @return byte[]
     */
    private byte[] getClass(String name) {
        try {
            return Files.readAllBytes(Paths.get(path + name.replace('.', File.separatorChar) + ".class"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}